package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.ArticleAdapter;
import com.xn.app.muying.bean.ToDayBean;
import com.xn.app.muying.fragment.SeekFragment;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyEditText;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Request;

/**
 * 搜索页面
 * Created by gaoge on 2016/11/9.
 */
public class SeekActivity extends BaseActivity implements View.OnClickListener, MyListView.IXListViewListener {

    //搜索框
    private EditText seek_edittext = null;
    //搜索按钮
    private TextView search_textview = null;
    //热门搜索列表
    private GridView gridview = null;
    //历史纪录列表
    private ListView listview = null;
    //数据显示listview
    private MyListView seek_listview = null;
    //显示搜索条数
    private TextView seek_listview_number = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //查看更多历史信息
    private RelativeLayout see_more = null;
    //搜索页面
    private LinearLayout linearlayout = null;
    //清除历史纪录
    private TextView clear_textview = null;
    //gridview适配器
    private GridViewListAdapter gridViewListAdapter = null;
    //listview适配器
    private ListViewAdapter listViewAdapter = null;
    //文章显示适配器
    private ArticleAdapter articleAdapter = null;
    //记录热门搜索数据
    private ArrayList<HashMap<String, String>> gridList = new ArrayList<HashMap<String, String>>();
    //记录历史数据
    private ArrayList<HashMap<String, String>> listList = new ArrayList<HashMap<String, String>>();
    //记录搜索结果
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    //点击项
    private int click = 0;
    //Fragment管理器
    private FragmentManager ragmentManager = null;
    //记录当前处于状态
    private boolean lean = true;
    //文本框左右图片
    Drawable drawableLeft = null;
    Drawable drawableRight = null;
    //加载框
    AlertDialog dialog;
    InputMethodManager imm;
    //记录数据是否加载完成
    private int number = 0;
    //数据库
    private DBManager db = null;
    //需要查询的数据
    private String data = "";
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number1 = 10;
    private Handler handler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek);
        //打开动画
//        overridePendingTransition(
//                android.R.anim.fade_in, android.R.anim.fade_out);
        //加载布局

        //初始化组件
        initialization();
        //实现
//        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization() {
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        db = new DBManager(this);
        seek_edittext = (EditText) findViewById(R.id.seek_edittext);
        seek_edittext.setSelection(seek_edittext.length());
        search_textview = (TextView) findViewById(R.id.search_textview);
        gridview = (GridView) findViewById(R.id.gridview);
        listview = (ListView) findViewById(R.id.listview);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        see_more = (RelativeLayout) findViewById(R.id.see_more);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        clear_textview = (TextView) findViewById(R.id.clear_textview);
        seek_listview = (MyListView) findViewById(R.id.seek_listview);
        seek_listview_number = (TextView) findViewById(R.id.seek_listview_number);
        search_textview.setOnClickListener(this);
        clear_textview.setOnClickListener(this);
        see_more.setOnClickListener(this);
        //listview 添加适配器
        articleAdapter = new ArticleAdapter(SeekActivity.this, list, imageLoader, options);
        seek_listview.setAdapter(articleAdapter);
        //文本框左右图标
        drawableLeft = getResources().getDrawable(R.mipmap.seek);
        drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
        drawableRight = getResources().getDrawable(R.mipmap.seek_delete);
        drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());

        //gridview每一项点击事件
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                click = i;
//                gridViewListAdapter.notifyDataSetInvalidated();
                seek_edittext.setText(gridList.get(i).get("word"));
                seek_edittext.setSelection(seek_edittext.length());
                /**隐藏软键盘**/
                closeTheKeyboard();
                //查询
                submitSearch(gridList.get(i).get("word"));
            }
        });
        //listview每一项点击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seek_edittext.setText(listList.get(i).get("word"));
                seek_edittext.setSelection(seek_edittext.length());
                /**隐藏软键盘**/
                closeTheKeyboard();
                //查询
                submitSearch(listList.get(i).get("word"));
            }
        });

        // 文本框监听
        seek_edittext.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (s.length() > 0) {
                    search_textview.setText("搜索");
                } else {
                    search_textview.setText("取消");
                }

            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                    loginHandler.sendEmptyMessage(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //listview 每一项点击
        seek_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list.size() != 0) {
                    Intent intent = new Intent();
                    intent.setClass(SeekActivity.this, EducationDetailsActivity.class);
                    intent.putExtra("type", 1);
                    intent.putExtra("id", list.get(position).get("id"));//添加头部视图，0被占用，所以索引从1开始
                    intent.putExtra("name", list.get(position).get("name"));
                    intent.putExtra("title", list.get(position).get("title"));
                    intent.putExtra("content", list.get(position).get("shortDescription"));
                    intent.putExtra("pic", list.get(position).get("pictureUrl"));
                    startActivity(intent);
                }
            }
        });
    }

    /**
     * 功能实现
     */
    private void realize() {
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(SeekActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            getListData();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }

    }

    /**
     * 单击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //搜索框
            case R.id.seek_edittext:
                break;
            //搜索按钮
            case R.id.search_textview:
                if (search_textview.getText().toString().equals("搜索")) {
                    /**隐藏软键盘**/
                    closeTheKeyboard();
                    data = seek_edittext.getText().toString();
                    if (data.length() > 0) {
                        dialog = new MyAlertDialog().ShowDialog(SeekActivity.this, R.layout.dialog_loading);
                        dialog.setCancelable(true);
                        list = new ArrayList<HashMap<String, String>>();
                        seek_listview.setSelection(0);
                        totalCount = 0;
                        currentPage = 1;
                        //查询数据
                        submitSearch(data);
                    } else {
                        ToastUtil.showToast(this, "请输入关键词查询");
                    }
                } else {
                    finish();
                }
                break;
            //清除历史纪录
            case R.id.clear_textview:
                listList = new ArrayList<HashMap<String, String>>();
                loginHandler.sendEmptyMessage(2);
                //删除方法
                deleteHistory();
                /**隐藏软键盘**/
                closeTheKeyboard();
                break;
            //点击查看历史更多
            case R.id.see_more:
                linearlayout.setVisibility(LinearLayout.GONE);
                /**隐藏软键盘**/
                closeTheKeyboard();
                break;
        }
    }

    /**
     * 向服务器查询数据
     *
     * @param data
     */
    private void submitSearch(final String data) {

        HttpUtil.getData(APIMethod.SearchArticle(data, currentPage, number1), handler, new HttpUtil.OnGetDataListener() {
            @Override
            public void onJsonData(String data) {
                try {
                    String bodys =data;
                    if (bodys!=null&&bodys.length()>0) {
                        JSONObject jsonObject = new JSONObject(bodys);
                        //获取数据总量
                        if (totalCount == 0) {
                            totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
                        }

                        JSONArray items = jsonObject.getJSONArray("items");
                        if (items.length() > 0) {
                            for (int i = 0; i < items.length(); i++) {
                                JSONObject object = items.getJSONObject(i);
                                String title = object.optString("title");
                                String pictureUrl = object.optString("pictureUrl");
                                String shortDescription = object.optString("shortDescription");
                                String id = object.optString("id");
                                JSONObject jsonObject1 = new JSONObject(object.optString("category"));
                                String name = jsonObject1.optString("name");
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("title", title);
                                map.put("pictureUrl", pictureUrl);
                                map.put("shortDescription", shortDescription);
                                map.put("id", id);
                                map.put("name", name);
                                list.add(map);
                            }

                            if (linearlayout.getVisibility() != View.GONE) {
                                linearlayout.setVisibility(View.GONE);
                            }
                            if (seek_listview_number.getVisibility() != View.VISIBLE) {
                                seek_listview_number.setVisibility(View.VISIBLE);
                            }
                            if (seek_listview.getVisibility() != View.VISIBLE) {
                                seek_listview.setVisibility(View.VISIBLE);
                            }
                            if (no_data_linearlayout.getVisibility() != View.GONE) {
                                no_data_linearlayout.setVisibility(LinearLayout.GONE);
                            }
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            onLoad();
                            seek_listview.setPullLoadEnable(true);
                            seek_listview.setXListViewListener(SeekActivity.this, totalCount, currentPage, number1);
                            articleAdapter.getData(list);
                            seek_edittext.setText("");
                            seek_listview_number.setText("共查找到" + totalCount + "条相关内容");
                        } else {
                            loginHandler.sendEmptyMessage(5);
                        }
                    } else {
                        loginHandler.sendEmptyMessage(5);
                    }
                } catch (Exception e) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    //提交删除操作
    private void deleteHistory() {


    }

    /**
     * 下载数据
     *
     * @return
     */
    public void getListData() {

        //热门标签
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.Seek()).get().build();
                    okhttp3.Response response = null;
                    response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    if (!bodys.equals("")) {
                        JSONObject jsonObject = JSONUtil.strToJson(bodys);
                        bodys = jsonObject
                                .getJSONArray("items").toString();
                        if (bodys != null && !bodys.equals("") && !bodys.equals("[]")) {
                            gridList = JSONUtil.jsonAryToListMap(jsonObject
                                    .getJSONArray("items"));
                            loginHandler.sendEmptyMessage(1);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        历史列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.SeekLiShi).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = null;
                    response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    if (!bodys.equals("")) {
                        JSONObject jsonObject = JSONUtil.strToJson(bodys);
                        bodys = jsonObject
                                .getJSONArray("items").toString();
                        if (bodys != null && !bodys.equals("") && !bodys.equals("[]")) {
                            listList = JSONUtil.jsonAryToListMap(jsonObject
                                    .getJSONArray("items"));
                            loginHandler.sendEmptyMessage(2);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (dialog != null) {
                dialog.dismiss();
            }
            try {
                switch (msg.what) {
                    //热门列表
                    case 1:
                        number = number + 1;
                        gridViewListAdapter = new GridViewListAdapter(SeekActivity.this, gridList);
                        gridview.setAdapter(gridViewListAdapter);
                        linearlayout.setVisibility(LinearLayout.VISIBLE);
                        break;
                    //历史列表
                    case 2:
                        number = number + 1;
                        if (listList.size() > 0) {
                            listViewAdapter = new ListViewAdapter(SeekActivity.this, listList);
                            listview.setAdapter(listViewAdapter);
                            listview.setVisibility(ListView.VISIBLE);
                            no_data_linearlayout.setVisibility(LinearLayout.GONE);
                            see_more.setVisibility(RelativeLayout.VISIBLE);
                        } else {
                            listview.setVisibility(ListView.GONE);
                            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                            see_more.setVisibility(RelativeLayout.GONE);
                        }
                        break;
                    //打开键盘
                    case 3:
                        imm = (InputMethodManager) seek_edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                        break;
                    //查询结果为有数据
                    case 4:
//
                        break;
                    //查询结果为无数据
                    case 5:
                        if (seek_listview_number.getVisibility() != View.GONE) {
                            seek_listview_number.setVisibility(View.GONE);
                        }
                        if (linearlayout.getVisibility() != View.GONE) {
                            linearlayout.setVisibility(View.GONE);
                        }
                        if (no_data_linearlayout.getVisibility() != View.VISIBLE) {
                            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                        }
                        if (seek_listview.getVisibility() != View.GONE) {
                            seek_listview.setVisibility(View.GONE);
                        }
                        seek_edittext.setText("");
                        break;
                    default:
                        break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    };

    /**
     * 热门列表适配器
     */
    class GridViewListAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public GridViewListAdapter(Context context,
                                   ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            //只显示8条数据
            if (getData.size() < 8) {
                return getData.size();
            } else {
                return 8;
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.seek_gridview_item, null);
                viewHolder.textview = (TextView) convertView.findViewById(R.id.textview);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textview.setText(getData.get(position).get("word"));
            //按钮控制
//            if (click == position) {
//                viewHolder.textview.setTextColor(SeekActivity.this.getResources().getColor(R.color.sys_fen));
//                viewHolder.textview.setBackgroundResource(R.drawable.button_white);
//            }else{
//                viewHolder.textview.setTextColor(SeekActivity.this.getResources().getColor(R.color.bj_color));
//                viewHolder.textview.setBackgroundResource(R.drawable.yuanjiao_baise);
//            }
            return convertView;
        }
    }

    /**
     * 历史列表适配器
     */
    class ListViewAdapter extends BaseAdapter {
        LayoutInflater lf = null;
        ArrayList<HashMap<String, String>> getData = new ArrayList<HashMap<String, String>>();
        ViewHolder viewHolder = null;

        public ListViewAdapter(Context context,
                               ArrayList<HashMap<String, String>> getData) {
            lf = LayoutInflater.from(context);
            this.getData = getData;
        }

        @Override
        public int getCount() {
            //只显示3条数据
            if (getData.size() < 5) {
                return getData.size();
            } else {
                return 5;
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = lf.inflate(R.layout.seek_listview_item, null);
                viewHolder.textview = (TextView) convertView.findViewById(R.id.textview);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.textview.setText(getData.get(position).get("word"));
            return convertView;
        }
    }

    /**
     * 包装类
     */
    private static class ViewHolder {
        private TextView textview = null;
    }


    /**
     * 隐藏键盘
     */
    private void closeTheKeyboard() {

        if (seek_edittext != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(seek_edittext.getWindowToken(), 0);
        }
    }

    /**
     * 关闭页面
     */
    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //上拉加载更多
    @Override
    public void onLoadMore() {
            if (totalCount > currentPage * number1) {
                currentPage = currentPage + 1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(AppConstant.THREAD_SLEEP);
                            //查询数据
                            submitSearch(data);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            } else {
                onLoad();
            }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        seek_listview.stopLoadMore();
    }
}
